package com.kinptm.masterclock.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.kinptm.masterclock.MasterClockApplication;
import com.kinptm.masterclock.bean.AlarmClock;
import com.kinptm.masterclock.bean.SpeedTime;
import com.kinptm.masterclock.bean.TimerRecord;

import java.sql.SQLException;

/**
 * Created by pc on 13-11-13.
 */
public class DbHelper extends OrmLiteSqliteOpenHelper {
    private static final String DATABASE_NAME = "alarm";
    private static final int DATABASE_VERSION = 6;
    private static DbHelper instance;

    public static DbHelper getInstance() {
        if (instance == null) {
            instance = new DbHelper(MasterClockApplication.getInstance());
        }
        return instance;
    }

    private DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, AlarmClock.class);
            TableUtils.createTable(connectionSource, SpeedTime.class);
            TableUtils.createTable(connectionSource, TimerRecord.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) {
        try {
            TableUtils.dropTable(connectionSource, AlarmClock.class, true);
            TableUtils.dropTable(connectionSource, SpeedTime.class, true);
            TableUtils.dropTable(connectionSource, TimerRecord.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public RuntimeExceptionDao<AlarmClock, Integer> getAlarmClockDao() {
        return getRuntimeExceptionDao(AlarmClock.class);
    }

    public RuntimeExceptionDao<TimerRecord, Integer> getTimerRecordDao() {
        return getRuntimeExceptionDao(TimerRecord.class);
    }

}
